import { useUserStore } from "../store/user";
import constants from "../utils/constants";

const userStore = useUserStore();

const header = {
    'Content-Type': 'application/json',
    'authentication': userStore.getUserToken // 确保调用方法获取 token
};

export function getConnectionSocket() {
    wx.connectSocket({
        url: `ws://localhost:8080/ws/user/reminder/${userStore.userInfo.id}`,
        header: header,
        success: (res) => {
            console.log('WebSocket连接成功2');
        },
        // fail: (err) => {
        //     console.log('WebSocket连接失败', err);
        //     wx.showToast({
        //         title: 'WebSocket连接失败，请重试',
        //         icon: 'none'
        //     });
        // }
    });

    // 监听 WebSocket 连接打开事件
    wx.onSocketOpen(() => {
      console.log(1);
        const data = {
            targetId: 2,
            phone: userStore.userNextInfo.phone,
            name: userStore.userNextInfo.name,
            message: '首次建立连接',
            status: 0
        };
        wx.sendSocketMessage({
            data: JSON.stringify(data),
            success: (res) => {
                console.log('首次连接消息发送成功');
            },
            fail: (err) => {
                console.log('首次连接消息发送失败', err);
            }
        });
    });
}

export function sendMessage() {
  let socketOpen = false
  let socketMsgQueue = []
  wx.onSocketOpen(function(res) {
    socketOpen = true
    for (let i = 0; i < socketMsgQueue.length; i++){
      sendSocketMessage(socketMsgQueue[i])
    }
    socketMsgQueue = []
  })
  
   const msg = {
     "id": 2,
     "targetId": 3,
     "phone": "13377776666",
     "name": "王五",
     "message": "感谢您的反馈，团队会及时处理！",
     "status": 1
   };
  if (socketOpen) {
    wx.sendSocketMessage({
      data:msg
    })
  } else {
    socketMsgQueue.push(msg)
  }
     //  const msg = {
     //    "id": 2,
     //    "targetId": 3,
     //    "phone": "13377776666",
     //    "name": "王五",
     //    "message": "感谢您的反馈，团队会及时处理！",
     //    "status": 1
     //  };
     // wx.sendSocketMessage({
     //    data: JSON.stringify(msg),
     //    success: () => console.log('消息发送成功:', msg),
     //    fail: err => console.error('消息发送失败:', err)
     //  });
}

export function closeConnectionSocket() {
    wx.closeSocket();
    console.log('关闭连接');
}